package com.webridge.plm.test;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.collections.WTCollection;
import wt.folder.Cabinet;
import wt.folder.Folder;
import wt.folder.FolderHelper;
import wt.folder.SubFolder;
import wt.folder.SubFolderReference;
import wt.inf.container.PrincipalSpec;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerHelper;
import wt.inf.container.WTContainerRef;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.org.DirectoryContextProvider;
import wt.org.OrganizationServicesHelper;
import wt.org.WTGroup;
import wt.org.WTUser;
import wt.pdmlink.PDMLinkProduct;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;

import com.webridge.plm.util.WCUtil;

public class FolderTestS implements RemoteAccess{
    
    
    public  static final String[] PRODUCTNAMES = new String[]{"Drive System","GOLF_CART"};
    public static Logger LOGGER = Logger.getLogger(FolderTestS.class.getName());
    public static void main(String[] args) throws IOException {
        
        RemoteMethodServer rms = RMIClient.getRMS();
//        RemoteMethodServer rms = RemoteMethodServer.getDefault();
//        rms.setUserName("wcadmin");
//        rms.setPassword("wcadmin");
        System.out.println("RMS test.");
        try {
            rms.invoke("exportFolder", FolderTestS.class.getName(), null, null, null);
            rms.invoke("getAllUsers", FolderTestS.class.getName(), null, null, null);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    
    
    
    public static void exportFolder() throws WTException{
        for(int i=0;i<PRODUCTNAMES.length;i++){
            String productName = PRODUCTNAMES[i];
            PDMLinkProduct product = (PDMLinkProduct) WCUtil.getWtContainerByName(productName);
            Cabinet cabinet = FolderHelper.service.getCabinet("Default", WTContainerRef.newWTContainerRef(product));
            Map<Folder, List<Folder>> map = new HashMap<Folder, List<Folder>>();
            ReferenceFactory rf = new ReferenceFactory();
            WTCollection collection = FolderHelper.service.getAllDescendantFolders(rf.getReference(cabinet));
            for(Object obj:collection)
            {
                SubFolder sunfolder=(SubFolder)((SubFolderReference)obj).getObject();
                getSubFolders(sunfolder,map);
            }
            Set<Folder> keys = map.keySet();
            Iterator<Folder> it = keys.iterator();
            while(it.hasNext()){
                Folder tmpFolder = (Folder) it.next();
                List<?> tmpList = (List<?>) map.get(tmpFolder);
                LOGGER.debug("Folder:" + tmpFolder.getName()+",subFolder:"+tmpList);
            }
            }
        
        
        
    }
    
    public static void getSubFolders(Folder folder, Map<Folder, List<Folder>> map) throws WTException {
        List<Folder> list = map.get(folder);
        if (list == null) {
            list = new ArrayList<Folder>();
        }
        QueryResult qr = FolderHelper.service.findSubFolders(folder);
        while (qr.hasMoreElements()) {
            Folder subFolder = (Folder) qr.nextElement();
            LOGGER.debug("Folder:" + folder.getName() + "\tsubFolder:" + subFolder.getName());
            list.add(subFolder);
        }
        map.put(folder, list);

        if (list != null && list.size() > 0) {
            for (Folder f : list) {
                getSubFolders(f, map);
            }
        }
    }
    
    /**
     * 获取系统中所有的用户及其相关信息；
     */
    public static void getAllUsers(){
        try {
            
            //Get all user Groups of one Organization start 2020-04-14
            PrincipalSpec localPrincipalSpec = new PrincipalSpec();
            try {
              WTContainer paramWTContainer =  getContainer("Demo Organization");
            localPrincipalSpec.setContainerReference(WTContainerRef.newWTContainerRef(paramWTContainer ));
              localPrincipalSpec.setPerformLookup(false);
              localPrincipalSpec.setIncludeAllServices(false);
            } catch (WTPropertyVetoException localWTPropertyVetoException) {
              throw new WTException(localWTPropertyVetoException);
            } catch (Exception e) {
                e.printStackTrace();
            }
            

            DirectoryContextProvider[] arrayOfDirectoryContextProvider = getPublicContextProviders(localPrincipalSpec);
            for (Object localObject2 : arrayOfDirectoryContextProvider) {
              ((DirectoryContextProvider)localObject2).setInternalGroupsSearchCriteria(null);
            }
            
            Enumeration enumGroup = findLikeGroups("*", arrayOfDirectoryContextProvider[0]);
           List orgGroupList = new ArrayList<String>();
            while (enumGroup.hasMoreElements()) {
              WTGroup localWTGroup = (WTGroup)enumGroup.nextElement();
              String groupName = localWTGroup.getName();
              orgGroupList.add(localWTGroup.getName());
              LOGGER.debug("Orgnization groupName:" + groupName);
            }
            LOGGER.debug("All Orgnization groupName:" + orgGroupList);

          //Get all user Groups of one Organization End 2020-04-14
            
            
            
            
            
            QuerySpec query = new QuerySpec(WTUser.class);
            QueryResult pqr = PersistenceHelper.manager.find(query);
            while(pqr.hasMoreElements()){
                WTUser user = (WTUser) pqr.nextElement();
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("username", user.getName());
                map.put("email", user.getEMail());
                map.put("fullname", user.getFullName());
                Enumeration<?> groupEnum = user.parentGroupNames();
                Set<String>groupSet = new HashSet<String>();
                while(groupEnum.hasMoreElements()){
                    String groupName  = (String) groupEnum.nextElement();
                    if(orgGroupList.contains(groupName))
                        {
                        groupSet.add(groupName);
                        }else{
                            LOGGER.debug("Illeagle Group name:"+groupName);

                        }
                }
                map.put("Group", groupSet); 
                LOGGER.debug("all User Info:" + map);
                
            }
        } catch (QueryException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (WTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        
        
    }
    public static Enumeration findLikeGroups(String paramString, DirectoryContextProvider paramDirectoryContextProvider) throws WTException {
        return OrganizationServicesHelper.manager.findLikeGroups(paramString, paramDirectoryContextProvider);
      }
    public static DirectoryContextProvider[] getPublicContextProviders(PrincipalSpec paramPrincipalSpec) throws WTException
    {
      return WTContainerHelper.service.getPublicContextProviders(paramPrincipalSpec);
    }
    
    /**
     * 
     * @param containerName
     * @return
     * @throws Exception
     */
    public static WTContainer getContainer(String containerName) throws Exception {
        if (!RemoteMethodServer.ServerFlag) {
            return (WTContainer) RemoteMethodServer.getDefault().invoke("getContainer", FolderTestS.class.getName(), null,
                    new Class[] { String.class }, new Object[] { containerName });
        }
        boolean access = SessionServerHelper.manager.setAccessEnforced(false);
        WTContainer wto = null;
        if (containerName == null || "".equals(containerName)) {
            return null;
        }
        try {
            QuerySpec qs = new QuerySpec(WTContainer.class);
            SearchCondition sc = new SearchCondition(WTContainer.class, WTContainer.NAME, SearchCondition.EQUAL, containerName);
            qs.appendWhere(sc);
            QueryResult qr = PersistenceHelper.manager.find(qs);
            Enumeration e = qr.getEnumeration();
            if (e.hasMoreElements()) {
                wto = (WTContainer) e.nextElement();
            }
        } catch (WTException e) {
            e.printStackTrace();
            throw e;
        } finally {
            SessionServerHelper.manager.setAccessEnforced(access);
        }
        return wto;
    }
}
